# Start log file for script -----------------------------------------------
TeachingDemos::txtStart("./log files/figureA17_full_prep.txt")

# Load Data ---------------------------------------------------------
# individual data
load("./data/impdat20.Race.WeekWeight.rdata")

# Equalizing weeks with Nationscape
impdat20.WeekWeight$week2 <- as.numeric(impdat20.WeekWeight$week) + 1
impdat20.WeekWeight$week2[which(impdat20.WeekWeight$week2 == 53)] <-  52
impdat20.WeekWeight$week2 <- as.character(impdat20.WeekWeight$week2)
impdat20.WeekWeight$week2[which(nchar(impdat20.WeekWeight$week2) == 1)] <- paste0("0", impdat20.WeekWeight$week2[which(nchar(impdat20.WeekWeight$week2) == 1)])
impdat20.WeekWeight <- fastDummies::dummy_cols(impdat20.WeekWeight, select_columns = "week2")

impdat20.WeekWeight$week2_post <- "Pre-GF"
for(i in 22:52){
  impdat20.WeekWeight$week2_post[which(impdat20.WeekWeight[, paste0("week2_", i)] == 1)] <- paste("Week", i)
}

# Models --------------------------------------------------------------
# full pre-post
m1_prepost <- lm(D_biep.White_Good_all ~ post_gf +
                   ideo_mod + ideo_con +
                   age_cat4 + edu_cat4 + race3 + sex +
                   census_region + broughtwebsite2,
                 data = impdat20.WeekWeight, weights = WeekWeights)
summary(m1_prepost)


# Weekly after
m1_pre_weeklypost <- lm(D_biep.White_Good_all ~ week2_post +
                          ideo_mod + ideo_con +
                          age_cat4 + edu_cat4 + race3 + sex +
                          census_region + broughtwebsite2,
                        data = impdat20.WeekWeight, weights = WeekWeights)
summary(m1_pre_weeklypost)


# Plot --------------------------------------------------------------------
prepost <- summary(m1_prepost)
weekly <- summary(m1_pre_weeklypost)
week_names <- grep("week", rownames(weekly$coefficients), value = T)
coef_out <- array(NA, c(length(week_names)+1,3))
coef_out <- as.data.frame(coef_out)
names(coef_out) <- c("var", "coef", "se")
coef_out[1,"var"] <- "Post GF, May 26, 2020-Dec 31, 2020"
coef_out[1,c("coef", "se")] <- prepost$coefficients[2, c("Estimate", "Std. Error")]
coef_out[-1, "var"] <- gsub("week2_post", "", week_names)
coef_out[-1,c("coef", "se")] <- weekly$coefficients[week_names,c("Estimate", "Std. Error")]
coef_out$var <- as.factor(coef_out$var)
coef_out$var <- factor(coef_out$var,
                       levels = rev(levels(coef_out$var)))
coef_out$indx <- c(1, rep(0, length(week_names)))
coef_out$indx <- ifelse(coef_out$indx == 1, "Pre-Post", "Weekly Indicators")

coef_out_Fsamp <- coef_out

# End log file for script -------------------------------------------------
TeachingDemos::txtStop()